--
-- Author: yawei.zhu
-- Date: 2018-05-10 19:41:34
--
-- BranchTaskPanel
--

local BranchTaskRender = import(".renders.BranchTaskRender")

local ClassRef = app.mvc.createPanelClass(...)

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.TaskSideSubRootNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._branchListView = self._ui["Panel/ListView"]
    self._branchListView:removeAllItems()

    local Panel = self._ui["Panel"]
    local bg = self._ui["Panel/bg03"]

    -- local headNode = cc.uiloader:load(Res.TaskSideItemNode)
    -- local headPanel = headNode:getChildByName("Panel")
    -- local headSize = headPanel:getContentSize()

    -- headNode:setPosition(cc.p(0, bg:getPositionY() + bg:getContentSize().height / 2 - headSize.height))
    -- headNode:addTo(Panel)

    -- local name = headPanel:getChildByName("name")
    -- name:setString(L("泰萨瑞姆"))

    self._noticeLabel = display.newTTFLabel({
        text = L("task_branch_desc1"),
        size = 20,
        color = display.COLOR_BLACK,
    })
   self._noticeLabel:setAnchorPoint(cc.p(0.5, 0.5))
   self._noticeLabel:setPosition(cc.p(bg:getPositionX(), bg:getPositionY() + bg:getContentSize().height / 2 - 20))
   self._noticeLabel:setVisible(false)
   self._noticeLabel:addTo(Panel)

    -- local listSize = self._branchListView:getContentSize()
    -- self._branchListView:setContentSize(cc.size(listSize.width, listSize.height - headSize.height))
end

function ClassRef:refresh()
    local branchTasks = self._onOperate("getBranchTasks")
    for i = 1, #branchTasks do
        local render = BranchTaskRender.create()
        render:onBtnClick(self._onOperate)
        render:setData(branchTasks[i])
        self._branchListView:pushBackCustomItem(render)
    end

    self._noticeLabel:setVisible(false)
    if #branchTasks <= 0 then
        self._noticeLabel:setVisible(true)
    end
end

function ClassRef:updateBranchTrackTask(taskId)
    local items = self._branchListView:getItems()
    for i, item in ipairs(items) do
        local data = item:getData()
        if data:getId() == taskId then
            item:setBtnTrack(true)
        else
            item:setBtnTrack(false)
        end
    end
end

function ClassRef:getBranchTaskBack(taskId)
    if not taskId then return end

    -- 支线任务领奖之后，服务器会把该支线任务清除，所以这里要单独去设置按钮
    -- local taskInfo = UD:getTaskById(taskId)
    -- if not taskInfo then return end

    local items = self._branchListView:getItems()
    for _, item in ipairs(items) do
        if item:getData():getId() == taskId then
            item:getBranchTaskBack()
            break
        end
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
